module delay_sampel
#(	
	parameter max_sample_frequency=200_000_000,
	parameter test_frequency_max=32'd200_0_000,
	parameter sampel_point_number=32'd100
)
(
	input				clk_250m		,
	input				rst_n			,
	
	input	[7:0]		ad_data			,
	input				en_sample		,
	input	[31:0]		test_frequency	,
	
	output		 		wrdata_clk		,
	output	reg [7:0]	wrdata

);

reg clk_judge;
reg [31:0] reg_test_frequency;
//如果en_sampel按下则将检测到的频率存储下以进行自动改变采样频率
always@(posedge clk_250m or negedge rst_n)
	if(!rst_n) begin
		reg_test_frequency <= 32'd10_000_000;
		clk_judge <= 1'b0;
	end
	else if(en_sample) begin
		if((test_frequency <= 32'd11_000)) begin
			reg_test_frequency <= test_frequency / 2;
			// if(test_frequency >= 32'd4000)
				// reg_test_frequency <= test_frequency / 2;
			// else if(test_frequency >= 32'd1000)
				// reg_test_frequency <= test_frequency / 4;
			// else
				// reg_test_frequency <= test_frequency;
		end
		else 
			reg_test_frequency <= test_frequency;
		
		if((test_frequency >= test_frequency_max) || test_frequency == 32'd0)
			clk_judge <= 1'b0;
		else begin
			clk_judge <= 1'b1;
			
		end
	end
	else begin
		reg_test_frequency <= reg_test_frequency; 
		clk_judge <= clk_judge;
	end

reg wrdata_clk_slow;
reg [31:0] cnt_clk_slow;//时钟计数
wire [31:0] yshang;
//采样频率
always@(posedge clk_250m or negedge rst_n)
	if(!rst_n) begin
		cnt_clk_slow <= 32'd0;
		wrdata_clk_slow <= 1'b0;
		wrdata <= 8'd0;
	end
	else if(clk_judge == 1'b0)begin
		cnt_clk_slow <= 32'd0;
		wrdata <= ad_data;
		wrdata_clk_slow <= 1'b1;
	end
	else if(cnt_clk_slow >= yshang) begin//max_sample_frequency/reg_test_frequency/sampel_point_number
		cnt_clk_slow <= 32'd0;
		wrdata <= ad_data;
		wrdata_clk_slow <= 1'b1;
	end
	else begin
		cnt_clk_slow <= cnt_clk_slow + 1'b1;
		wrdata_clk_slow <= 1'b0;
		wrdata <= wrdata;
	end
	
		//硬件除法模块
	drive_division  drive_division_1(  
		.	clk			(clk_250m),
		.	en			(1'b1),
		.	dividend	(max_sample_frequency/sampel_point_number), //被除数  
		.	divisor		(reg_test_frequency),  //除数
					
		.	yshang		(yshang),//商数  
		.	yyushu 		() //余数
	);

		
	reg clk_125m;
	//125M的时钟
	always @(posedge clk_250m or negedge rst_n)	
		if(!rst_n) begin
			clk_125m <= 1'b0;
		end
		else begin
			clk_125m <= ~clk_125m;
		end

//采样时钟选择
assign wrdata_clk = (clk_judge)? wrdata_clk_slow : 1'b1;
	
endmodule
